package com.boot2.core.web;

import com.alibaba.fastjson.JSONObject;
import com.boot2.core.SysProperties;
import com.boot2.core.conf.UrlProperties;
import com.boot2.core.constant.CoreConstant;
import com.boot2.core.constant.HttpConstant;
import com.boot2.core.dict.ErrorCode;
import com.boot2.core.model.vo.Result;
import com.boot2.core.utils.CheckUtil;
import com.boot2.core.utils.ResultBuilder;
import com.boot2.core.utils.ServletUtil;
import com.google.common.collect.Lists;
import lombok.Setter;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * 系统级拦截,所有全拦
 *
 * @author zhangweilin
 * @version V1.0
 * @date 2016年4月19日 下午12:15:07
 * @description
 */
@Component
public class SysInterceptor implements HandlerInterceptor {

    /**
     * 获取环境信息
     */
    @Autowired
    Environment env;

    @Autowired
    CookieProcessor cookieProcessor;

    @Autowired(required = false)
    SysProperties sysProperties;

    @Setter
    private List<Integer> errorCodes = Lists.newArrayList(404, 500);

    public SysInterceptor() {
    }

    @SneakyThrows
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!handErrorPage(request,response)) {
            return false;
        }

        RequestContext requestContext = RequestContext.get();
        if (null != requestContext) {
            //todo 此行貌似可能会有bug
            requestContext.setHandler(handler);
            RequestContext.setRequest(request);
            RequestContext.setResponse(response);
        } else {
            RequestContext.start(request, response, handler);
        }
        cookieProcessor.warpCookie();
        return true;
    }

    private boolean handErrorPage(HttpServletRequest request,HttpServletResponse response) throws IOException {
        if (null != sysProperties) {
            UrlProperties url = sysProperties.getUrl();
            if (url != null) {
                Map<String, String> custom = url.getCustom();
                if (CheckUtil.isNotEmpty(custom)) {
                    String errorPage = custom.get(CoreConstant.errorPageKey);
                    if (CheckUtil.isNotEmpty(errorPage)) {
                        int status = response.getStatus();
                        //此时，不是真正的ajax请求,那么页面跳转
                        if (ServletUtil.isAjaxRequest(request)&&!sysProperties.getIsAjax()) {
                            //如果是ajax请求
                            if (status == Integer.valueOf(ErrorCode.code_404)) {
                                Result<Object> result = ResultBuilder.buildResult(ErrorCode.code_404, "url not found");
                                String json = JSONObject.toJSONString(result);
                                response.setContentType(HttpConstant.contentTypeJsonUTF8);
                                PrintWriter writer = response.getWriter();
                                writer.write(json);
                                writer.flush();
                                return false;
                            }
                        } else {
                            //非ajax请求，出错则按配置跳转
                            if (CheckUtil.isNotEmpty(errorCodes)) {
                                for (int i = 0; i < errorCodes.size(); i++) {
                                    int errorCode = errorCodes.get(i);
                                    if (errorCode == status) {
                                        response.sendRedirect(errorPage);
                                        return false;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//		String fullUrl = ServletUtil.getFullUrl();
//		// 那个登录页不记录
//		if (!fullUrl.contains("/logout") && !(null != CoreUrlConstant.loginPageUrl && fullUrl.contains(CoreUrlConstant.loginPageUrl))
//				&& !fullUrl.contains("favicon.ico") && !request.getMethod().equalsIgnoreCase("post")) {
//			request.getSession().setAttribute(CoreConstant.currentFullUrlSessionKey, fullUrl);
//		}
//        RequestContext requestContext = RequestContext.get();
//        if (null != requestContext) {
//            RequestContext.get().clearContext();
//        }
    }
}
